// 主应用类 - 简约设计
class App {
    constructor() {
        this.chartManager = null;
        this.studentManager = null;
        this.init();
    }

    // 初始化应用
    init() {
        this.initManagers();
        this.bindGlobalEvents();
        this.showWelcomeMessage();
    }

    // 初始化管理器
    initManagers() {
        // 初始化图表管理器
        this.chartManager = new ChartManager();
        
        // 初始化学生管理器
        this.studentManager = new StudentManager();
        
        // 将学生管理器暴露到全局作用域
        window.studentManager = this.studentManager;
    }

    // 绑定全局事件
    bindGlobalEvents() {
        // 窗口大小变化事件
        window.addEventListener('resize', this.handleResize.bind(this));
        
        // 键盘快捷键
        document.addEventListener('keydown', this.handleKeyboard.bind(this));
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
    }

    // 处理窗口大小变化
    handleResize() {
        // 重新调整图表大小
        if (this.chartManager) {
            Object.values(this.chartManager.charts).forEach(chart => {
                if (chart && typeof chart.resize === 'function') {
                    chart.resize();
                }
            });
        }
    }

    // 处理键盘快捷键
    handleKeyboard(event) {
        // Ctrl/Cmd + K: 聚焦搜索框
        if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
            event.preventDefault();
            const searchInput = document.querySelector('input[placeholder="搜索学生姓名/学号"]');
            if (searchInput) {
                searchInput.focus();
            }
        }
        
        // Ctrl/Cmd + N: 添加新学生
        if ((event.ctrlKey || event.metaKey) && event.key === 'n') {
            event.preventDefault();
            if (this.studentManager) {
                this.studentManager.showAddStudentModal();
            }
        }
        
        // Escape: 关闭模态框
        if (event.key === 'Escape') {
            const modal = document.querySelector('.fixed');
            if (modal) {
                modal.remove();
            }
        }
    }

    // 处理页面可见性变化
    handleVisibilityChange() {
        if (document.hidden) {
            // 页面隐藏时的处理
            console.log('页面已隐藏');
        } else {
            // 页面显示时的处理
            console.log('页面已显示');
            // 刷新图表数据
            if (this.chartManager) {
                this.chartManager.addChartAnimations();
            }
        }
    }

    // 显示欢迎消息
    showWelcomeMessage() {
        // 检查是否是首次访问
        const isFirstVisit = !localStorage.getItem('hasVisited');
        if (isFirstVisit) {
            this.showNotification('欢迎使用第二课堂素质拓展学分评定系统！', 'info');
            localStorage.setItem('hasVisited', 'true');
        }
    }

    // 显示通知
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 p-4 rounded-md shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500 text-white' :
            type === 'error' ? 'bg-red-500 text-white' :
            type === 'warning' ? 'bg-yellow-500 text-white' :
            'bg-blue-500 text-white'
        }`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    // 获取应用状态
    getAppStatus() {
        return {
            chartManager: !!this.chartManager,
            studentManager: !!this.studentManager,
            totalStudents: this.studentManager ? this.studentManager.students.length : 0,
            warningStudents: this.studentManager ? this.studentManager.getWarningStudents().length : 0
        };
    }

    // 刷新应用数据
    refreshData() {
        if (this.studentManager) {
            this.studentManager.renderStudents();
            this.studentManager.updatePagination();
        }
        
        if (this.chartManager) {
            this.chartManager.addChartAnimations();
        }
        
        this.showNotification('数据已刷新', 'success');
    }

    // 导出应用数据
    exportWarningData() {
        if (!this.studentManager) return;
        
        // 显示导出选项对话框
        this.showExportOptionsDialog();
    }

    // 显示导出选项对话框
    showExportOptionsDialog() {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        
        modal.innerHTML = `
            <div class="bg-white rounded-lg shadow-lg max-w-md w-full mx-4">
                <div class="bg-gray-50 px-6 py-4 rounded-t-lg border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900">导出学生数据</h3>
                </div>
                <div class="p-6">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">导出格式</label>
                            <select id="exportFormat" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                <option value="csv">CSV文件</option>
                                <option value="json">JSON文件</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">警示等级筛选</label>
                            <div class="space-y-2">
                                <label class="flex items-center">
                                    <input type="checkbox" value="danger" checked class="rounded text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">严重警告</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" value="warning" checked class="rounded text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">一般警告</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" value="info" checked class="rounded text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">提醒通知</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 rounded-b-lg flex justify-end space-x-3">
                    <button onclick="this.closest('.fixed').remove()" class="px-4 py-2 text-gray-600 hover:text-gray-800">
                        取消
                    </button>
                    <button onclick="window.app.performExport()" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                        导出
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
    }

    // 执行导出操作
    performExport() {
        const format = document.getElementById('exportFormat').value;
        const selectedLevels = Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(cb => cb.value);
        
        // 关闭对话框
        document.querySelector('.fixed').remove();
        
        // 获取当前筛选后的学生数据
        let students = this.studentManager.filteredStudents || this.studentManager.students;
        
        // 应用警示等级筛选
        students = students.filter(student => selectedLevels.includes(student.warningLevel));
        
        if (students.length === 0) {
            this.showNotification('没有符合条件的数据可导出', 'warning');
            return;
        }
        
        if (format === 'csv') {
            this.exportAsCSV(students);
        } else if (format === 'json') {
            this.exportAsJSON(students);
        }
    }

    // 导出为CSV格式
    exportAsCSV(students) {
        // 定义CSV表头
        const headers = ['学号', '姓名', '院系', '专业', '已获学分', '警示等级', '最后通知'];
        
        // 转换数据为CSV行
        const rows = students.map(student => {
            return [
                student.id,
                student.name,
                student.department,
                student.major,
                student.credits,
                this.getWarningLevelText(student.warningLevel),
                student.lastNotified || ''
            ].map(value => `"${value.toString().replace(/"/g, '\"')}"`).join(',');
        });
        
        // 组合CSV内容
        const csvContent = `${headers.join(',')}\n${rows.join('\n')}`;
        
        // 创建并下载CSV文件
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        this.downloadFile(blob, `警示学生名单_${new Date().toISOString().split('T')[0]}.csv`);
        
        this.showNotification('CSV文件导出成功', 'success');
    }

    // 导出为JSON格式
    exportAsJSON(students) {
        // 转换为JSON格式
        const jsonContent = JSON.stringify(students, null, 2);
        
        // 创建并下载JSON文件
        const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' });
        this.downloadFile(blob, `警示学生名单_${new Date().toISOString().split('T')[0]}.json`);
        
        this.showNotification('JSON文件导出成功', 'success');
    }

    // 下载文件辅助方法
    downloadFile(blob, fileName) {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 导入应用数据
    // 导入CSV格式的学生警示数据
    importData(file) {
        if (!file) return;
        
        // 验证文件类型
        if (!file.name.endsWith('.csv')) {
            this.showNotification('请上传CSV格式文件', 'error');
            return;
        }
        
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const csvContent = e.target.result;
                const lines = csvContent.split('\n').filter(line => line.trim() !== '');
                
                // 验证表头
                const headers = lines[0].split(',').map(h => h.replace(/^"|"$/g, '').trim());
                const expectedHeaders = ['学号', '姓名', '院系', '专业', '已获学分', '警示等级', '最后通知'];
                
                if (!this.arraysEqual(headers, expectedHeaders)) {
                    this.showNotification('CSV文件格式不正确，表头不匹配', 'error');
                    return;
                }
                
                // 解析数据行
                const students = [];
                for (let i = 1; i < lines.length; i++) {
                    const line = lines[i];
                    const values = line.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(v => v.replace(/^"|"$/g, ''));
                    
                    if (values.length !== expectedHeaders.length) {
                        this.showNotification(`第${i+1}行数据格式不正确`, 'error');
                        continue;
                    }
                    
                    // 创建学生对象
                    const student = {
                        id: values[0],
                        name: values[1],
                        department: values[2],
                        major: values[3],
                        credits: parseFloat(values[4]),
                        warningLevel: this.getWarningLevelFromText(values[5]),
                        lastNotified: values[6]
                    };
                    
                    students.push(student);
                }
                
                // 更新学生数据
                this.studentManager.students = students;
                this.studentManager.filteredStudents = [...students];
                this.studentManager.renderStudents();
                this.studentManager.updatePagination();
                this.showNotification(`成功导入${students.length}条学生警示数据`, 'success');
            } catch (error) {
                this.showNotification('文件解析失败: ' + error.message, 'error');
            }
        };
        reader.readAsText(file);
    }
    
    // 辅助方法：比较两个数组是否相等
    arraysEqual(arr1, arr2) {
        if (arr1.length !== arr2.length) return false;
        return arr1.every((val, index) => val === arr2[index]);
    }
    
    // 辅助方法：从文本获取警示等级
    getWarningLevelFromText(text) {
        switch(text) {
            case '严重警告': return 'danger';
            case '一般警告': return 'warning';
            case '提醒通知': return 'info';
            default: return 'info';
        }
    }
    
    // 销毁应用
    destroy() {
        if (this.chartManager) {
            this.chartManager.destroy();
        }
        
        // 移除事件监听器
        window.removeEventListener('resize', this.handleResize.bind(this));
        document.removeEventListener('keydown', this.handleKeyboard.bind(this));
        document.removeEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
    }
}

// 应用初始化
document.addEventListener('DOMContentLoaded', () => {
    // 创建应用实例
    window.app = new App();
    
    // 绑定导入按钮事件
    const importFileInput = document.getElementById('importFileInput');
    if (importFileInput) {
        importFileInput.addEventListener('change', (e) => {
            if (e.target.files[0]) {
                window.app.importData(e.target.files[0]);
                // 重置input值，允许重复选择同一文件
                importFileInput.value = '';
            }
        });
    }
    
    // 绑定导出按钮事件
    const exportButton = document.querySelector('button:has(i.fa-download)');
    if (exportButton) {
        exportButton.addEventListener('click', () => {
            window.app.exportData();
        });
    }
    
    console.log('第二课堂素质拓展学分评定系统已启动');
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (window.app) {
        window.app.destroy();
    }
});

// 导出应用类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = App;
}